package cn.zzq.userscenter.springmvc.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import cn.zzq.userscenter.auth.pojo.AMenu;
import cn.zzq.userscenter.auth.pojo.ARoleMenu;
import cn.zzq.userscenter.auth.service.IAuthService;
import cn.zzq.userscenter.common.controller.BaseController;
import cn.zzq.userscenter.common.util.ConstatFinalUtil;
import cn.zzq.userscenter.common.util.PageInfoUtil;
import cn.zzq.userscenter.users.pojo.AAdmins;
import cn.zzq.userscenter.users.pojo.ARole;
import cn.zzq.userscenter.users.service.IUsersService;

/**
 * 不需要登陆就可以访问的Controller
 * 
 * @author WangshSxt
 */
@Controller
@RequestMapping("/back/admins")
public class AdminsLoginController extends BaseController
{
	@Resource
	private IUsersService usersService;
	@Resource
	private IAuthService authService;

	/**
	 * 调到登录后的主页面
	 */
	@RequestMapping("/main")
	public String main()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---main---");
		return "/back/admins/main";
	}

	/**
	 * 切换菜单
	 */
	@RequestMapping("/left_menu")
	public String left_menu()
	{
		ConstatFinalUtil.SYS_LOGGER.info("---left_menu--");
		return "/back/admins/left_menu";
	}

	/*
	 * 管理员操作开始
	 */
	@RequestMapping("/adminsList")
	public String adminList(String keyword, String status, String st, String ed, Model model, String currentPage,
			String pageSize)
	{
		ConstatFinalUtil.SYS_LOGGER.info("----adminsList----");
		// 将字符串变成时间
		if (st == null)
		{
			st = "";
		}
		if (ed == null)
		{
			ed = "";
		}
		if (status == null)
		{
			status = "";
		}

		/* 搜索条件 */
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("keyword", keyword);
		if (!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}
		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			/*
			 * 将字符串转换成日期
			 * 
			 * 完善了DateFormatUtil
			 */
			stDate = this.dateFormatUtil.strDateTime(st);
			edDate = this.dateFormatUtil.strDateTime(ed);
			;
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);

		PageInfoUtil pageInfoUtil = proccedPageInfo(currentPage, pageSize);

		/* 查询结果 */
		Map<String, Object> resultMap = this.usersService.findCondListAdminsService(pageInfoUtil, condMap);
		List<AAdmins> adminsList = (List<AAdmins>) resultMap.get("adminsList");
		pageInfoUtil = (PageInfoUtil) resultMap.get("pageInfoUtil");
		/* 将结果放到四大作用域中 */
		model.addAttribute("adminsList", adminsList);
		model.addAttribute("pageInfoUtil", pageInfoUtil);

		/* 将查询条件放到request中 */
		model.addAttribute("keyword", keyword);
		model.addAttribute("status", status);
		model.addAttribute("st", st);
		model.addAttribute("ed", ed);
		return "/back/admins/adminsList";
	}

	/**
	 * 打开管理员添加页面
	 */
	@RequestMapping("/adminsInsert")
	public String adminsInsert(Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("----adminsInsert----");
		/* 查询所有的角色 */
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersService.findCondListRoleService(null, condMap);
		model.addAttribute("roleList", roleList);
		return "/back/admins/adminsInsert";
	}

	/**
	 * 提交管理员添加操作
	 */
	@RequestMapping(value = "/adminsInsertSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String adminsInsertSubmit(AAdmins admins, HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("-----adminsInsertSubmit------");
		// 密码加密
		admins.setPassword(this.encryptUtil.encodeStr(admins.getPassword()));
		// 时间
		admins.setCreateTime(new Date());
		admins.setUpdateTime(new Date());
		admins.setLastLoginTime(new Date());
		// 存储数据
		JSONObject resDBJSON = this.usersService.saveOneAdminsService(admins);
		// 信息
		this.info = resDBJSON.get("info") + "";
		JSONObject resultJSON = printJuiJson(request, info);
		return resultJSON.toJSONString();
	}

	/**
	 * 打开管理员更新页面
	 */
	@RequestMapping("/adminsUpdate")
	public String adminsUpdate(Model model, String aid)
	{
		ConstatFinalUtil.SYS_LOGGER.info("----adminsUpdate----");
		/* 查询所有的角色 */
		Map<String, Object> condMap = new HashMap<>();
		/* 根据id查询管理员 */
		condMap.put("id", aid);
		AAdmins admins = this.usersService.findOneAdminsService(condMap);
		model.addAttribute("admins", admins);
		/* 查询角色 */
		condMap.clear();
		condMap.put("status", "1");
		List<ARole> roleList = this.usersService.findCondListRoleService(null, condMap);
		model.addAttribute("roleList", roleList);
		return "/back/admins/adminsUpdate";
	}

	/**
	 * 提交管理员更新操作
	 */
	@RequestMapping(value = "/adminsUpdateSubmit", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String adminsUpdateSubmit(AAdmins admins, HttpServletRequest request)
	{
		ConstatFinalUtil.SYS_LOGGER.info("----adminsUpdateSubmit---");
		Map<String, Object> condMap = new HashMap<>();
		condMap.put("id", admins.getId());
		AAdmins adminsDB = this.usersService.findOneAdminsService(condMap);
		// 更新表存在的字段
		adminsDB.setEmail(admins.getEmail());
		adminsDB.setName(admins.getName());
		adminsDB.setPhone(admins.getPhone());
		adminsDB.setQq(admins.getQq());
		adminsDB.setSex(admins.getSex());
		adminsDB.setStatus(admins.getStatus());

		adminsDB.setUpdateTime(new Date());

		JSONObject resDBJSON = this.usersService.updateOneAdminsService(adminsDB);
		this.info = resDBJSON.get("info") + "";
		JSONObject resultJOSN = printJuiJson(request, info);

		return resultJOSN.toJSONString();
	}

	/*
	 * 管理员操作结束
	 */

	/*
	 * 菜单模块开始
	 */

	/* 菜单列表 */
	@RequestMapping("menuList")
	public String menuList(String keyword, String status, String st, String ed, Model model, String currentPage,
			String pageSize)
	{
		ConstatFinalUtil.SYS_LOGGER.info("----menuList----");

		// 将字符串变成时间
		if (st == null)
		{
			st = "";
		}
		if (ed == null)
		{
			ed = "";
		}
		if (status == null)
		{
			status = "";
		}

		Map<String, Object> condMap = new HashMap<>();
		condMap.put("keyword", keyword);
		// 判断状态
		if (!"".equalsIgnoreCase(status))
		{
			condMap.put("status", status);
		}

		// 判断时间
		Date stDate = null;
		Date edDate = null;
		if (!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			/*
			 * 将字符串转换成日期
			 * 
			 * 完善了DateFormatUtil
			 */
			stDate = this.dateFormatUtil.strDateTime(st);
			edDate = this.dateFormatUtil.strDateTime(ed);
			;
		}
		condMap.put("stDate", stDate);
		condMap.put("edDate", edDate);

		// 分页
		PageInfoUtil pageInfoUtil = new PageInfoUtil();
		List<AMenu> menuList = this.authService.findCondListMenuService(pageInfoUtil, condMap);

		if (menuList != null)
		{
			model.addAttribute("pageInfoUtil", pageInfoUtil);
			model.addAttribute("menuList", menuList);
			model.addAttribute("keyword", keyword);
			model.addAttribute("status", status);
			model.addAttribute("stDate", stDate);
			model.addAttribute("edDate", edDate);
		}

		return "back/admins/menuList";
	}

	/* 菜单树形结构 */
	@RequestMapping("menuTreeList")
	public String menuTreeList(Model model)
	{
		ConstatFinalUtil.SYS_LOGGER.info("-----menuTreeList----");
		// 拼装树形结构的菜单
		String result = this.authService.proccedMenuTreeStr("menu", "");
		model.addAttribute("result",result);
		return "back/admins/menuTreeList";
	}

	/*
	 * 菜单模块结束
	 */
	
	
	/**
	 * 权限分配模块开始
	 */
	
	//权限分配页面
	@RequestMapping("/roleMenuInsert")
	public String roleMenuInsert(String roleId,Model model){
		ConstatFinalUtil.SYS_LOGGER.info("-----roleMenuInsert-----");
		
		//拼装字符串
		String result = this.authService.proccedMenuTreeStr("roleMenu", roleId);
		model.addAttribute("result",result);
		return "/back/admins/roleMenuInsert";
	}
	
	//权限分配操作
	@RequestMapping(value = "/roleMenuInsertSubmit",produces="text/html;charset=UTF-8")
	@ResponseBody
	public String roleMenuInsertSubmit(HttpServletRequest request,String[] menuId,String roleId){
		ConstatFinalUtil.SYS_LOGGER.info("--roleMenuInsertSubmit:{}",Arrays.toString(menuId));
		this.info = "操作失败";
		if(menuId != null){
			int totalCount = menuId.length;
			int succeedCount = 0;
			int failedCount = 0;
		
			
			//删除旧数据
			Map<String, Object> condMap = new HashMap<>();
			condMap.put("roleId", roleId);
			this.authService.deleteOneRoleMenuService(condMap);
			
			for(int i = 0;i < menuId.length;i++){
				String meId = menuId[i];
				
				try
				{
					ARoleMenu roleMenu = new ARoleMenu();
					roleMenu.setMenuId(Integer.valueOf(meId));
					roleMenu.setRoleId(Integer.valueOf(roleId));
					roleMenu.setCreateTime(new Date());
					roleMenu.setUpdateTime(new Date());
					roleMenu.setPubTime(new Date());
					JSONObject resultDBJSON = this.authService.saveOneRoleMenuService(roleMenu);
					if("0".equalsIgnoreCase(resultDBJSON.getString("code"))){
						succeedCount ++;
					}else{
						failedCount ++;
					}
				} catch (Exception e)
				{
					failedCount ++;
				}
			}
			//拼装提示信息
			this.info = "操作成功，总条数：" + totalCount + ",成功：" + succeedCount+",失败：" + failedCount;
		}
		
		ConstatFinalUtil.SYS_LOGGER.info("权限分配，信息：{},roleId:{},菜单:{}",this.info,roleId,Arrays.toString(menuId));
		JSONObject resultJOSN = this.printJuiJson(request, info);
		return resultJOSN.toJSONString();
	}
	
	
	
	/**
	 * 权限分配模块结束
	 */

	/**
	 * 退出登录
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session)
	{
		ConstatFinalUtil.SYS_LOGGER.info("---logout---");
		session.removeAttribute("admins");
		return "/back/login";
	}
}
